//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.service;

import com.kun.framework.core.util.DateUtils;
import com.kun.framework.web.web.vo.ValueLabelVo;
import com.kun.portal.util.QueryHelper;
import com.kun.portal.webframe.dao.FwRoleDao;
import com.kun.portal.webframe.dao.FwTeamDao;
import com.kun.portal.webframe.dao.FwUserDao;
import com.kun.portal.webframe.po.FwRolePo;
import com.kun.portal.webframe.po.FwTeamPo;
import com.kun.portal.webframe.po.FwUserPo;
import com.kun.portal.webframe.vo.Teams;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.CriteriaBuilder.In;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FwUserService {
    @Autowired
    private FwUserDao fwuserDao;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private FwRoleDao fwRoleDao;
    @Autowired
    private FwTeamDao fwTeamDao;

    public FwUserService() {
    }

    public Page<FwUserPo> queryAll(Pageable pageable) {
        return this.fwuserDao.findAll(pageable);
    }

    public Page<FwUserPo> findByCreatorAndUserNameContainingOrderByUserIdDesc(String userId, String userName, Pageable pageable) {
        return this.fwuserDao.findByCreatorAndUserNameContainingOrderByUserIdDesc(userId, userName, pageable);
    }

    public FwUserPo addFwUser(FwUserPo fwuser) throws Exception {
        return this.updateFwUser(fwuser);
    }

    public List<FwUserPo> findAllUsers(){
//        Query query=  entityManager.createQuery("select new com.kun.portal.webframe.po.SelectableUserUserView(s,u) from ServiceItemToSelectableUsersPo s right JOIN FwUserPo u on s.selectAbleUser.userId = u.userId");
//        return query.getResultList();

        return  fwuserDao.findAll();
    }

    @Transactional
    public FwUserPo updateFwUser(FwUserPo fwuser) throws Exception {
        fwuser.setUserName(fwuser.getUserName().trim());
        fwuser.setUserCnName(fwuser.getUserCnName().trim());
        if(StringUtils.isNoneBlank(fwuser.getPhone())){
            fwuser.setPhone(fwuser.getPhone().trim());
        }

        if(StringUtils.isNoneBlank(fwuser.getEmail())){
            fwuser.setEmail(fwuser.getEmail().trim());
        }

        String userId = fwuser.getUserId();
        String errMsg = null;
        FwUserPo userNamePo = this.fwuserDao.findByUserName(fwuser.getUserName());
        FwUserPo userCnNamePo = this.fwuserDao.findByUserCnName(fwuser.getUserCnName());
//        FwUserPo phonePo = this.fwuserDao.findByPhone(fwuser.getPhone());
//        FwUserPo emailPo = this.fwuserDao.findByEmail(fwuser.getEmail());
        if(userNamePo != null && !userNamePo.getUserId().equals(userId)) {
            errMsg = errMsg == null?"用户名已被注册":errMsg + "；用户名已被注册";
        }

        if(userCnNamePo != null && !userCnNamePo.getUserId().equals(userId)) {
            errMsg = errMsg == null?"用户中文名已被注册":errMsg + "；用户中文名已被注册";
        }

//        if(phonePo != null && !phonePo.getUserId().equals(fwuser.getUserId())) {
//            errMsg = errMsg == null?"手机号已被注册":errMsg + "；手机号已被注册";
//        }
//
//        if(emailPo != null && !emailPo.getUserId().equals(userId)) {
//            errMsg = errMsg == null?"邮箱已被注册":errMsg + "；邮箱已被注册";
//        }

        if(errMsg != null) {
            throw new Exception(errMsg);
        } else {
            FwUserPo fwuserPo = (FwUserPo)this.fwuserDao.save(fwuser);
            return fwuserPo;
        }
    }

    @Transactional
    public void deleteFwUser(String userId) {
        this.fwuserDao.delete(userId);
    }

    public List<FwUserPo> findFwUserByCreator(String creatorId) {

        return fwuserDao.findAll();
    }

    public List<String> findFwUserByRoleId(String roleId) {
        Query query = this.entityManager.createNativeQuery("select r.user_id from fw_role_user r where r.role_id=?1");
        query.setParameter(1, roleId);
        return query.getResultList();
    }

    public List<String> findFwUserByTeamId(String teamId) {
        Query query = this.entityManager.createNativeQuery("select r.user_id from fw_team_user r where r.team_id=?1");
        query.setParameter(1, teamId);
        return query.getResultList();
    }

    public List<String> findFwTeamByUserId(String userId) {
        Query query = this.entityManager.createNativeQuery("select r.team_id from fw_team_user r where r.user_id=?1");
        query.setParameter(1, userId);
        return query.getResultList();
    }

    @Transactional
    public void updateFwRoleUserByUserId(List<String> userIds, String roleId) {
        FwRolePo role = (FwRolePo)this.fwRoleDao.findOne(roleId);
        List<FwUserPo> userList = this.fwuserDao.findAll(userIds);
        Iterator var6 = userList.iterator();

        while(var6.hasNext()) {
            FwUserPo user = (FwUserPo)var6.next();
            user.addRole(role);
        }

        this.fwuserDao.save(userList);
    }

    @Transactional
    public void updateFwTeamUserByTeamId(List<String> userIds, String teamId) {
        FwTeamPo team = (FwTeamPo)this.fwTeamDao.findOne(teamId);
        List<FwUserPo> userList = this.fwuserDao.findAll(userIds);
        Iterator var6 = userList.iterator();

        while(var6.hasNext()) {
            FwUserPo user = (FwUserPo)var6.next();
            user.addTeam(team);
        }

        this.fwuserDao.save(userList);
    }

    public Page<FwUserPo> findFwUserByTeamsAndUserNameLike(Set<FwTeamPo> teams, String userName, Pageable pageable) {
        return this.fwuserDao.findByTeamsAndUserNameLike(teams, userName, pageable);
    }

    @Transactional
    public void updateFwUserStatus(String userId, String status) {
        FwUserPo userPo = (FwUserPo)this.fwuserDao.findOne(userId);
        userPo.setModifyTime(DateUtils.getNowDate());
        userPo.setUserStatus(status);
        this.fwuserDao.save(userPo);
    }

    public List<FwUserPo> findSelectUserByTeamId(String teamId) {
        Query query = this.entityManager.createNativeQuery("SELECT user_id userId,user_name userName,user_cn_name userCnName FROM fw_user a WHERE a.user_status!=0 and EXISTS (SELECT * FROM fw_team_user b WHERE a.user_id=b.user_id AND b.team_id=?)");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        query.setParameter(1, teamId);
        return query.getResultList();
    }

    public List<FwUserPo> findAllUser() {
        Query query = this.entityManager.createNativeQuery("SELECT user_id userId,user_name userName,user_cn_name userCnName FROM fw_user a  WHERE a.user_status!=0 ");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List<FwUserPo> findNotSelectUserByTeamId(String parentId, String teamId) {
        Query query;
        if(StringUtils.isEmpty(parentId)) {
            query = this.entityManager.createNativeQuery("SELECT user_id userId,user_name userName,user_cn_name userCnName FROM fw_user a  WHERE a.user_status!=0 AND NOT EXISTS (SELECT * FROM fw_team_user b WHERE a.user_id=b.user_id AND b.team_id=?)");
            query.setParameter(1, teamId);
        } else {
            query = this.entityManager.createNativeQuery("SELECT a.user_id userId, a.user_name userName, a.user_cn_name userCnName FROM fw_user a  WHERE a.user_status!=0 AND NOT EXISTS (SELECT * FROM fw_team_user d WHERE a.user_id=d.user_id AND d.team_id=?1)");
            query.setParameter(1, teamId);
        }

        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List<FwUserPo> findNotSelectUserByRoleId(String roleId) {
        String teamId = ((FwRolePo)this.fwRoleDao.findOne(roleId)).getTeamId();
        Query query = this.entityManager.createNativeQuery("SELECT d.user_id userId,d.user_name userName,d.user_cn_name userCnName  FROM (SELECT a.* FROM fw_user a,fw_team_user b  WHERE a.user_status!=0 AND a.user_id=b.user_id AND b.team_id=?1) d  WHERE NOT EXISTS (SELECT * FROM fw_role_user e WHERE d.user_id=e.user_id AND e.role_id=?2)");
        query.setParameter(1, teamId);
        query.setParameter(2, roleId);
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public List<FwUserPo> findSelectUserByRoleId(String roleId) {
        Query query = this.entityManager.createNativeQuery("SELECT user_id userId,user_name userName,user_cn_name userCnName FROM fw_user a WHERE a.user_status!=0 AND  EXISTS (SELECT * FROM fw_role_user b WHERE a.user_id=b.user_id AND b.role_id=?)");
        ((SQLQuery)query.unwrap(SQLQuery.class)).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        query.setParameter(1, roleId);
        return query.getResultList();
    }

    public FwUserPo findOne(String userId) {
        return (FwUserPo)this.fwuserDao.findOne(userId);
    }

    public Page<FwUserPo> findAll(Pageable pageable) {
        return this.fwuserDao.findAll(pageable);
    }

    public Page<FwUserPo> findAll(String key, Pageable pageable) {
        return this.fwuserDao.findAllByKey(key, pageable);
    }

    public List<FwUserPo> findByFwUserUnique(final Map<String, String> map) {
        return this.fwuserDao.findAll(new Specification<FwUserPo>() {
            public Predicate toPredicate(Root<FwUserPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicate = new ArrayList();
                Iterator var6 = map.keySet().iterator();

                while(var6.hasNext()) {
                    String key = (String)var6.next();
                    if(FwUserService.UniqueKey.valueOf(key) != null) {
                        String value = (String)map.get(key);
                        if(StringUtils.isNotBlank(value)) {
                            predicate.add(cb.equal(root.get(key).as(String.class), value));
                        }
                    }
                }

                Predicate[] p = new Predicate[predicate.size()];
                query.where(cb.and((Predicate[])predicate.toArray(p)));
                return query.getRestriction();
            }
        });
    }

    public Page<FwUserPo> queryWithParams(FwTeamPo fwTeam, final String key, Pageable pageable) {

        if(Teams.SysTeam.name().equals(fwTeam.getTeamId())) {
            Specification query = new Specification<FwUserPo>() {
                public Predicate toPredicate(Root<FwUserPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    if(StringUtils.isNotBlank(key)) {
                        List<Predicate> ps = new ArrayList();
                        ps.add(cb.like(root.get("userName"), "%" + key.trim() + "%"));
                        ps.add(cb.like(root.get("userCnName"), "%" + key.trim() + "%"));
                        query.where(cb.or((Predicate[])ps.toArray(new Predicate[0])));
                    }

                    return query.getGroupRestriction();
                }
            };
            return this.fwuserDao.findAll(query, pageable);
        } else {
            String sql = "select * from fw_user a where 1 = 1";
            List<Object> params = new ArrayList();
            String level = fwTeam.getTeamLevel();
            if(StringUtils.isNotBlank(key)) {
                String key2 = "%" + key.trim() + "%";
                sql = sql + " and ( a.user_name like ? or a.user_cn_name like ?)";
                params.add(key2);
                params.add(key2);
            }

            String teamId = fwTeam.getTeamId() + "%";
            if("1".equals(level)) {
                sql = sql + " and (exists(select 1 from fw_team_user b where b.user_id = a.user_id and b.team_id like ?)   or not exists(select 1 from fw_team_user b where b.user_id = a.user_id))";
                params.add(teamId);
            } else {
                sql = sql + " and exists(select 1 from fw_team_user b where b.user_id = a.user_id and b.team_id like ?)";
                params.add(teamId);
            }

            final Page<Map<String, Object>> users = QueryHelper.queryWithJdbc(sql, params.toArray(), pageable);
            List<FwUserPo> datas = this.fwuserDao.findAll(new Specification<FwUserPo>() {
                public Predicate toPredicate(Root<FwUserPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    In<String> in = cb.in(root.get("userId"));
                    Iterator var6 = users.iterator();

                    while(var6.hasNext()) {
                        Map<String, Object> map = (Map)var6.next();
                        in.value((String)map.get("user_id"));
                    }

                    query.where(cb.and(new Predicate[]{in}));
                    return query.getGroupRestriction();
                }
            });
            return new PageImpl(datas, pageable, users.getTotalElements());
        }
    }

    private static enum UniqueKey {
        userName,
        userCnName,
        phone,
        email;

        private UniqueKey() {
        }
    }
}
